<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh v-model="isFreshLoading" @refresh="onRefresh" success-text="更新成功">
      <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      success-duration="1500"
      @load="onLoad"
    >
      <article-item v-for="(article,index) in articles" :key="index"  :content="article"></article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticles } from '@/apis/article'
import ArticleItem from '@/components/ArticleItem'
import { debounce } from 'loadsh'
export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    ArticleItem // 文章内容组件
  },
  data () {
    return {
      articles: [],
      timestamp: null,
      loading: false,
      finished: false,
      isFreshLoading: false,
      scrollTop: 0
    }
  },
  created () {
  },
  mounted () {
    let articleList = this.$refs['article-list']
    articleList.onscroll = debounce(() => {
      this.scrollTop = articleList.scrollTop
    }, 500)
  },
  activated () {
    this.$refs['article-list'].scrollTop = this.scrollTop
  },
  deactivated () {
    console.log('失去活动')
  },
  methods: {
    async onLoad () {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      })
      const { results } = data.data
      this.articles.push(...results)
      // 加载状态结束
      this.loading = false

      if (results.length > 0) {
        this.timestamp = data.data.pre_timestamp
      } else {
        this.finished = true
      }
    },
    async onRefresh () {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1
      })
      const { results } = data.data
      this.articles.unshift(...results)
      this.isFreshLoading = false
    }
  }
}
</script>
<style lang="less" scoped>
.article-list{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 90px;
  overflow-y: auto;
}
</style>
